package com.arvin.faceDetect.camera

import android.graphics.*
import android.hardware.Camera
import android.media.ImageReader
import android.os.Handler
import android.os.HandlerThread
import android.util.Log
import android.util.Size
import android.view.Surface
import com.google.mlkit.vision.face.Face
import com.google.mlkit.vision.face.FaceLandmark
import com.arvin.faceDetect.model.CameraSettings
import com.arvin.faceDetect.callback.FaceDetectionCallback
import com.arvin.faceDetect.callback.PreviewCallback

class CameraManager private constructor() {
    companion object {
        private const val TAG = "CameraManager"
        
        @Volatile
        private var instance: CameraManager? = null
        
        fun getInstance(): CameraManager {
            return instance ?: synchronized(this) {
                instance ?: CameraManager().also { instance = it }
            }
        }
    }

    private var camera: Camera? = null
    private var cameraId: Int = 0
    private var previewSize: Size? = null
    private var imageReader: ImageReader? = null
    private var cameraThread: HandlerThread? = null
    private var cameraHandler: Handler? = null
    private var isProcessing = false
    private var isPreviewStarted = false
    private var isFaceDetectionEnabled = false
    private var isEyeTrackingEnabled = false
    private var showFaceRect = true
    private var showEyeRect = true
    private var faceDetectionCallback: FaceDetectionCallback? = null
    private var previewCallback: PreviewCallback? = null
    private var cameraSettingsCallback: CameraSettingsCallback? = null
    private var currentSettings = CameraSettings()
    private var isSettingsChanged = false

    fun setShowFaceRect(show: Boolean) {
        showFaceRect = show
        cameraSettingsCallback?.onShowFaceRectChanged(show)
    }

    fun setShowEyeRect(show: Boolean) {
        showEyeRect = show
        cameraSettingsCallback?.onShowEyeRectChanged(show)
    }

    fun isShowFaceRect(): Boolean = showFaceRect
    fun isShowEyeRect(): Boolean = showEyeRect

    fun setCameraSettingsCallback(callback: CameraSettingsCallback?) {
        cameraSettingsCallback = callback
    }

    fun setFaceDetectionCallback(callback: FaceDetectionCallback?) {
        faceDetectionCallback = callback
    }

    fun setPreviewCallback(callback: PreviewCallback?) {
        previewCallback = callback
    }

    fun getCurrentSettings(): CameraSettings = currentSettings

    fun updateSettings(settings: CameraSettings) {
        currentSettings = settings
        isSettingsChanged = true
        cameraSettingsCallback?.onSettingsChanged(settings)
        restartPreviewIfNeeded()
    }

    private fun restartPreviewIfNeeded() {
        if (isSettingsChanged && isPreviewStarted) {
            stopPreview()
            startPreview()
            isSettingsChanged = false
        }
    }

    fun startPreview() {
        if (!isPreviewStarted) {
            // 实现预览启动逻辑
            isPreviewStarted = true
        }
    }

    fun stopPreview() {
        if (isPreviewStarted) {
            // 实现预览停止逻辑
            isPreviewStarted = false
        }
    }

    private fun processImage(image: android.media.Image) {
        if (!isProcessing) {
            isProcessing = true
            try {
                val planes = image.planes
                val buffer = planes[0].buffer
                val data = ByteArray(buffer.remaining())
                buffer.get(data)
                val bitmap = BitmapFactory.decodeByteArray(data, 0, data.size)

                // 旋转图片
                val matrix = Matrix()
                matrix.postRotate(90f)
                val rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)

                // 检测人脸
                val faces = detectFaces(rotatedBitmap)
                
                // 绘制检测结果
                if (showFaceRect || showEyeRect) {
                    val canvas = Canvas(rotatedBitmap)
                    val paint = Paint().apply {
                        color = Color.RED
                        style = Paint.Style.STROKE
                        strokeWidth = 5f
                    }

                    faces.forEach { face ->
                        if (showFaceRect) {
                            canvas.drawRect(face.boundingBox, paint)
                        }
                        if (showEyeRect && face.getLandmark(FaceLandmark.LEFT_EYE) != null && face.getLandmark(FaceLandmark.RIGHT_EYE) != null) {
                            paint.color = Color.GREEN
                            val leftEye = face.getLandmark(FaceLandmark.LEFT_EYE)!!.position
                            val rightEye = face.getLandmark(FaceLandmark.RIGHT_EYE)!!.position
                            canvas.drawCircle(leftEye.x, leftEye.y, 10f, paint)
                            canvas.drawCircle(rightEye.x, rightEye.y, 10f, paint)
                        }
                    }
                }

                // 回调结果
                previewCallback?.onPreviewFrame(rotatedBitmap, faces)
            } catch (e: Exception) {
                Log.e(TAG, "处理图像失败", e)
            } finally {
                isProcessing = false
            }
        }
    }

    private fun detectFaces(bitmap: Bitmap): List<Face> {
        // TODO: 实现人脸检测逻辑
        return emptyList()
    }
}

interface CameraSettingsCallback {
    fun onShowFaceRectChanged(show: Boolean)
    fun onShowEyeRectChanged(show: Boolean)
    fun onSettingsChanged(settings: CameraSettings)
} 